/**
 * v-downLoad 下载文件
 * Copyright (c) 2022 ruoyi
 */

export default {
  beforeMount(el: any, { value, arg }: any) {
    if (arg === 'callback') {
      el.$downLoadCallback = value;
    } else {
      el.$downLoadValue = value;
      const handler = async () => {
        if (Array.isArray(el.$downLoadValue)) {
          for (let i = 0; i < el.$downLoadValue.length; i++) {
            await downloadFile(el.$downLoadValue[i]);
          }
        } else {
          await downloadFile(el.$downLoadValue);
          if (el.$downLoadCallback) {
            el.$downLoadCallback(el.$downLoadValue);
          }
        }
      };
      el.addEventListener('click', handler);
      el.$destroyDownLoad = () => el.removeEventListener('click', handler);
    }
  }
};

interface DownloadFile {
  blob?: Blob;
  url?: string;
  fileName?: string;
}

async function downloadFile(file: DownloadFile | string) {
  // eslint-disable-next-line no-async-promise-executor
  return new Promise(async (resolve) => {
    let blob: Blob;
    let fileName: string;

    if (typeof file === 'string') {
      // 处理URL字符串
      blob = await fetchBlob(file);
      fileName = getFileNameFromUrl(file);
    } else if (file.blob instanceof Blob) {
      // 处理Blob对象
      blob = file.blob;
      fileName = file.fileName || 'download';
    } else if (file.url) {
      // 处理包含URL的对象
      blob = await fetchBlob(file.url);
      fileName = file.fileName || getFileNameFromUrl(file.url);
    } else {
      console.error('Invalid file format');
      resolve(false);
      return;
    }

    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    resolve(true);
  });
}

async function fetchBlob(url: string): Promise<Blob> {
  url = url.replace(/^http:/, 'https:');
  const response = await fetch(url);
  return await response.blob();
}

function getFileNameFromUrl(url: string): string {
  const parts = url.split('/');
  let fileName = parts[parts.length - 1];
  // 移除查询参数
  fileName = fileName.split('?')[0];
  // 如果没有文件扩展名，添加.png
  if (!fileName.includes('.')) {
    fileName += '.png';
  }
  return fileName;
}
